package com.zhg.recorddemo

import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.MotionEvent
import android.view.TextureView
import android.view.View
import android.widget.FrameLayout
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.lmy.codec.texture.impl.filter.BaseFilter
import com.lmy.codec.texture.impl.filter.BeautyV4Filter
import com.lmy.codec.texture.impl.filter.GroupFilter
import com.lmy.codec.texture.impl.sticker.ImageSticker
import com.lmy.codec.texture.impl.sticker.TextSticker
import com.zhg.recorddemo.helper.SystemBarUtil
import com.zhg.videorecord.collect.CameraWrapper
import com.zhg.videorecord.encoder.Encoder
import com.zhg.videorecord.entity.CodecContext
import com.zhg.videorecord.helper.CodectUtil
import com.zhg.videorecord.presenter.VideoRecorder
import com.zhg.videorecord.presenter.impl.VideoRecorderV2Impl
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : BaseActivity(), View.OnTouchListener, RadioGroup.OnCheckedChangeListener {

    private lateinit var mRecorder: VideoRecorderV2Impl
    private lateinit var mFilterController: FilterController
    private var defaultVideoWidth = 0
    private var defaultVideoHeight = 0
    private var count = 0
    private var type=false;
    private lateinit var mTextureView:TextureView
    override fun initView() {
        var w=4
        var h=4;
        //nv21yyyyuv
        var size=w*h+4+4
        var src= ByteArray(size);
        var dst=ByteArray(size)
        for (i in 0 until 16){
            if (i<16){
                //Y分量每个像素都采集，共4*4个字节 从0-4*4
                src[i]=3
            }else{
                //每4个Y(像素采集一个U) U:16/4个
                //从16，到16+4是U
                //同理v有4个字节，从第20 ,到24 是U
            }
            src[16]=2;
            src[17]=1;
            src[18]=2;
            src[19]=1;
            src[20]=2;
            src[21]=1;
            src[22]=2;
            src[23]=1;
        }

        CodectUtil.convertNv21ToNv12(src, dst, w*h)


        isYougu="rk3288_box" == Build.MODEL

        SystemBarUtil.doShowSystemBar(this)
        ratioGroup.check(ratioGroup.getChildAt(0).id)
        cameraGroup.check(cameraGroup.getChildAt(0).id)
        ratioGroup.setOnCheckedChangeListener(this)
        cameraGroup.setOnCheckedChangeListener(this)
        //Init TextureView
        if (type){
            surfaceview.visibility=View.GONE;
             mTextureView = TextureView(this).apply {
                fitsSystemWindows = true
                keepScreenOn = true
                //  setOnTouchListener(this@MainActivity)
            }
            mTextureContainer.addView(mTextureView, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT))
        }else{
            surfaceview.visibility=View.VISIBLE;
            surfaceview.scaleY=-1f
        }

        tvStart.setOnClickListener {
            if (mRecorder.prepared()) {
                //继续录像
                mRecorder.start()
                tvStart.text="暂停"
            } else if (mRecorder.started()){
               mRecorder.pause()
                tvStart.text="继续"
                /* mRecorder.stop()
                tvStart.text="开始"
                mRecorder.reset()
                resetParam()
                mRecorder.prepare()*/
            }
        }
        nextBtn.setOnClickListener {
            nextBtn.isEnabled = false
            tvStart.text="开始"
            mRecorder.stop()
            mRecorder.reset()
            resetParam()
            mRecorder.prepare()
        }

        //某usb摄像头 第一组：w=1920，h=1080

        mRecorder = VideoRecorderV2Impl(this)
        mRecorder.reset()
           var time= SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.US).format(Date())
        //或者传入rtpm地址，进行推流
        mRecorder.setOutputUri("${Environment.getExternalStorageDirectory().absolutePath}/0a/test${time}.mp4")

        //mRecorder.setOutputUri("rtmp://192.168.2.104:1935/live/home")
        if (isYougu){
            mRecorder.setOutputSize(1920, 1080)//Default 720x1280
        }else{
            mRecorder.setOutputSize(1080, 1920)//Default 720x1280

            /**
             * desc：旋转预览方向使其与屏幕同向，(但这并不会改变onPreviewCallback返回的数据)
             * 一般手机的相机传感器方向与屏幕方向成90度(不管如何旋转手机都成90度(封装问题)，故需要旋转90
             * (真实画面:"↑"，传感器画面(竖握)："←",setOritation(90):"↑")
             * annotated by ZHG on 2020/4/21
             */
            mRecorder.setOritation(90)
        }
        resetParam()
        mRecorder.setFps(24)
        mRecorder.enableHardware(true)

        mRecorder.setCameraIndex(CameraWrapper.CameraIndex.BACK)
        mRecorder.setFilter(getDefaultFilter())
        if (type){
            mRecorder.setPreviewDisplay(mTextureView)
            mRecorder.setPreviewDataType(CodecContext.PreviewDataType.FrameAvailab)
        }else{
            mRecorder.setSurfaceView(surfaceview)
            mRecorder.setPreviewDataType(CodecContext.PreviewDataType.PreviewCallback)
        }
        mRecorder.setOnStateListener(onStateListener)
        mRecorder.prepare()
        mFilterController = FilterController(mRecorder, progressLayout)
        defaultVideoWidth = mRecorder.getWidth()
        defaultVideoHeight = mRecorder.getHeight()

        effectBtn.setOnClickListener {
            mFilterController.chooseFilter(this)
        }

    }

    override fun getLayoutResource(): Int {
      return  R.layout.activity_main
    }
    private var isYougu=false;
    private val youguPath="/mnt/usb_storage/SATA/C/oa"
    private fun resetParam(){
        val flag=true;
        var basePath=""
        if (isYougu&&File(youguPath).exists()){
            basePath=youguPath
        }else{
            basePath="${Environment.getExternalStorageDirectory().absolutePath}/0a"
        }
        var time= SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.US).format(Date())
        try {
            if (!File(basePath).exists()){
                File(basePath).mkdirs()
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        mRecorder.setOutputUri("${basePath}/recorddemo-${time}.mp4")
        // mRecorder.setOutputUri("rtmp://192.168.2.104:1935/live/home")

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
       // setContentView(R.layout.activity_main)

    }

    private fun getDefaultFilter(): BaseFilter {
        return GroupFilter.create(BeautyV4Filter())
                .addSticker(TextSticker().apply {
                    setText(TextSticker.Text("HWVC", 56f).apply {
                        x = 0.8f
                        y = 0.03f
                    })
                })
                .addSticker(ImageSticker().apply {
                    setImage(ImageSticker.Image().apply {
                        x = 0.03f
                        y = 0.03f
                        scale = 1.6f
                        bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_logo_hwvc)
                    })
                })
    }

    override fun onTouch(v: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                if (mRecorder.prepared())
                    mRecorder.start()
            }
            MotionEvent.ACTION_UP -> {
                if (mRecorder.started())
                    mRecorder.pause()
            }
        }
        return true
    }

    private var onStateListener =
            object : VideoRecorder.OnStateListener {
                override fun onError(error: Int, msg: String) {
                    AlertDialog.Builder(this@MainActivity)
                            .setCancelable(true)
                            .setTitle("ERROR")
                            .setMessage(msg).show()
                }

                override fun onStop() {

                }

                override fun onPrepared(encoder: Encoder) {
//                    mRecorder.start()
                    runOnUiThread {
                        enableChangeRatio(true)
                        nextBtn.isEnabled = true
                        timeView.text = "00:00.00"
                        tvDuration.text = "00:00.00"

                    }
                }

                override fun onRecord(encoder: Encoder, timeUs: Long) {
                    runOnUiThread {
                        timeView.text = formatTimeUs(timeUs)
                        tvDuration.text = formatTimeUs(timeUs)
                    }
                }
            }

    private fun formatTimeUs(timeUs: Long): String {
        val second = timeUs / 1000000
        var ms = (timeUs / 10000 % 100).toString()
        ms = if (1 == ms.length) "0$ms" else ms
        var s = (second % 60).toString()
        s = if (1 == s.length) "0$s" else s
        var m = (second / 60).toString()
        m = if (1 == m.length) "0$m" else m
        return "$m:$s.$ms"
    }

    private fun enableChangeRatio(enable: Boolean) {
        for (i in 0 until ratioGroup.childCount) {
            ratioGroup.getChildAt(i).isEnabled = enable
        }
    }

    override fun onCheckedChanged(group: RadioGroup, checkedId: Int) {
        when (group.id) {
            R.id.cameraGroup -> {
                val i = group.indexOfChild(group.findViewById(checkedId))
                if (0 == i)
                    mRecorder.setCameraIndex(CameraWrapper.CameraIndex.BACK)
                else
                    mRecorder.setCameraIndex(CameraWrapper.CameraIndex.FRONT)
            }
            R.id.ratioGroup -> {
                val width = mRecorder.getWidth()
                var height = when (group.indexOfChild(group.findViewById(checkedId))) {
                    1 -> {//1:1
                        width
                    }
                    2 -> {//4:3
                        (width / 4f * 3).toInt()
                    }
                    3 -> {//3:2
                        (width / 3f * 2).toInt()

                    }
                    else -> {//默认
                        defaultVideoHeight
                    }
                }
                if (0 != height % 2) {
                    ++height
                }
                enableChangeRatio(false)
                nextBtn.isEnabled = false
                mRecorder.stop()
                mRecorder.reset()
                mRecorder.setOutputSize(width, height)
                mRecorder.setOutputUri("${Environment.getExternalStorageDirectory().absolutePath}/test_${count++}.mp4")
                mRecorder.prepare()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mRecorder.release()
    }

}
